<?php
namespace app\api\controller;
use think\Controller;

class Base extends Controller
{
    public function initialize(){
    header("content-type:application/json;charset=utf-8");
    
    // 允许的域名列表
    $allowedOrigins = [
        'http://localhost:8080',
        'http://192.168.10.235:8080',
        'http://192.168.10.123:8082'
    ];
    
    // 获取请求的Origin头（可能不存在，需判断）
    $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
    
    // 如果请求来源在允许列表中，则设置对应的Access-Control-Allow-Origin
    if (in_array($origin, $allowedOrigins)) {
        header("Access-Control-Allow-Origin: {$origin}");
    }else{
        header("Access-Control-Allow-Origin: http://localhost:8080");
    }
    
    // 其他CORS配置
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
    header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS, PATCH');
    header('Access-Control-Allow-Credentials: true'); // 允许携带Cookie（此时不能用*）
    
    // 处理预检请求
    if (request()->isOptions()) {
        http_response_code(204);
        exit();
    }
}
	
}
